<?php

namespace App\Http\Controllers;

use App\Complain;
use Illuminate\Http\Request;
use App\Comzan;

class ComplainController extends Controller
{
    //页面渲染
    public function index()
    {
        $complains = Complain::orderBy('created_at', 'desc')->withCount("comzans")->with(['user'])->paginate(4);
        return view('complain/complain',compact('complains'));
    }
    //创建吐槽页面
    public function create()
    {
        return view('complain/cpcreate');
    }
    public function store()
    {
        //验证
        $this->validate(request(), [
            'title'=>'max:5',
            'content' => 'required|max:115',
        ]);
        $user_id = \Auth::id();
        $params = array_merge(request(['title','content']),compact('user_id'));
        Complain::create($params);
        return redirect('/complain');
    }
    //点赞功能
    public function zan(Complain $complain)
    {
        $comzan = new \App\Comzan;
        $comzan->user_id = \Auth::id();
        $complain->comzans()->save($comzan);
        return back();
    }

    /*
     * 取消点赞
     */
    public function unzan(Complain $complain)
    {
        $complain->comzan(\Auth::id())->delete();
        return back();
    }
}
